package com.aiti.lulian.utils;

import java.util.Random;

public class RandomCharUtil {

    public static void main(String[] args) {
        // 创建Random实例
        Random random = new Random();
        // 用于存储随机码的StringBuilder对象
        StringBuilder randomCode = new StringBuilder();
        // 包含数字和大写字母的字符串
        String characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        // 随机码的长度
        int length = 6;
        for (int i = 0; i < length; i ++) {
            // 从characters字符串中随机按选择一个字段
            int index = random.nextInt(characters.length());
            // 将随机字符添加到随机码中
            randomCode.append(characters.charAt(index));
        }
        System.out.println("生成的" + length + "位随机码为：" + randomCode);
    }

    /**
     * @param length 随机码的长度
     * @return
     */
    public static String generateRandomCode(int length) {
        // 创建Random实例
        Random random = new Random();
        // 用于存储随机码的StringBuilder对象
        StringBuilder randomCode = new StringBuilder();
        // 包含数字和大写字母的字符串
        String characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        // 随机码的长度
        for (int i = 0; i < length; i ++) {
            // 从characters字符串中随机按选择一个字段
            int index = random.nextInt(characters.length());
            // 将随机字符添加到随机码中
            randomCode.append(characters.charAt(index));
        }
        return randomCode.toString();
    }
}